// 文章列表

<template>
  <div>
    <!-- 顶部状态栏 -->
    <div class="user-status-bar">
      <template v-if="isLoggedIn">
        <span class="user-info">👤 {{ username || '用户' }}</span>
        <el-button size="small" @click="handleLogout" class="logout-btn">退出登录</el-button>
      </template>
      <template v-else>
        <el-button size="small" type="primary" @click="goToLogin" class="login-btn">登录</el-button>
      </template>
    </div>
    <div class="articles-container">
    <div class="carousel-section">
      <el-carousel height="340px" :interval="3500" arrow="always">
        <el-carousel-item v-for="(item, idx) in carouselImages" :key="idx">
          <div class="carousel-img-wrapper" @click="goToArticleDetail(item.id)" style="cursor:pointer;position:relative;">
            <img :src="item.url" :alt="item.alt" class="carousel-img" />
            <div class="carousel-caption">{{ item.caption }}</div>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>
    <div class="header-section">
      <h2>文章列表</h2>
      <div class="search-and-publish">
        <el-input
          v-model="searchQuery"
          placeholder="搜索文章标题或内容"
          clearable
          @input="handleSearch"
          class="search-input"
        ></el-input>
        <el-button type="primary" @click="goToPublishArticle" class="publish-button">编写文章</el-button>
      </div>
    </div>
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <div v-else class="article-list">
      <div v-for="article in filteredArticles" :key="article.id" class="article-card" @click="goToArticleDetail(article.id)">
        <h3 class="article-title">{{ article.title }}</h3>
        <div class="article-meta-footer">
          <p class="article-meta">
            <span class="author">作者: {{ article.authorName || '匿名用户' }}</span>
            <span class="time">发布时间: {{ formatTime(article.addedTime) }}</span>
          </p>
          <div class="article-body">
            <p v-if="article.body">{{ article.body }}</p>
            <p v-else class="no-body">暂无内容</p>
          </div>
          <div class="article-details-container">
            <div class="article-details">
              <span v-if="article.userid" class="detail-item">用户ID: {{ article.userid }}</span>
              <span v-if="article.categoryid" class="detail-item">分类ID: {{ article.categoryid }}</span>
              <span v-if="article.completed !== null" class="detail-item">状态: {{ article.completed ? '已完成' : '未完成' }}</span>
            </div>
            <el-button
              type="danger"
              size="small"
              @click.stop="handleDelete(article.id)"
              class="delete-button"
            >删除</el-button>
          </div>
        </div>
      </div>
      <div v-if="filteredArticles.length === 0 && !loading && !error" class="no-results">没有找到匹配的文章。</div>
    </div>
  </div>
  </div>
</template>

<script setup lang="ts">
// 轮播图图片数据通过文章API动态获取
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import axios from 'axios';
import { ElMessageBox, ElMessage } from 'element-plus';
// 用户状态栏相关
const userStore = useUserStore();
const isLoggedIn = computed(() => userStore.isLoggedIn);
const username = computed(() => userStore.currentUsername);
const goToLogin = () => {
  router.push('/login');
};

const handleLogout = () => {
  userStore.clearUser();
  router.push('/login');
};

interface CarouselItem {
  id: number;
  url: string;
  alt: string;
  caption: string;
}

const carouselImages = ref<CarouselItem[]>([]);

// 复用文章API，取前3条文章作为轮播内容
const fetchCarouselImages = async () => {
  try {
    const response = await fetch('/api/demo/getallitems');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    if (Array.isArray(data)) {
      // 随机选取三条
      const shuffled = data.slice().sort(() => Math.random() - 0.5);
      carouselImages.value = shuffled.slice(0, 3).map((item: any) => ({
        id: item.id,
        url: item.cover || 'https://images.unsplash.com/photo-1506744038136-46273834b3fb?auto=format&fit=crop&w=800&q=80',
        alt: item.title || '文章封面',
        caption: item.title || '精彩文章'
      }));
    }
  } catch (e) {
    // 失败时可设置默认图片
    carouselImages.value = [
      { id: 0, url: 'https://images.unsplash.com/photo-1506744038136-46273834b3fb?auto=format&fit=crop&w=800&q=80', alt: '默认', caption: '欢迎来到文章分享平台' }
    ];
  }
};

interface Article {
  id: number;
  title: string;
  body: string | null;
  addedTime: string;
  userid: number | null;
  completed: boolean | null;
  categoryid: number | null;
  authorName: string | null;
}

const articles = ref<Article[]>([]);
const loading = ref(true);
const error = ref<string | null>(null);
const router = useRouter();

const fetchArticles = async () => {
  try {
    const response = await fetch('/api/demo/getallitems');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    if (Array.isArray(data)) {
      articles.value = data;
    } else {
      articles.value = data;
    }
  } catch (e: any) {
    error.value = '获取文章失败: ' + e.message;
  } finally {
    loading.value = false;
  }
};

const formatTime = (timeString: string) => {
  if (!timeString) return '未知时间';
  try {
    const date = new Date(timeString);
    return date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }).replace(/\//g, '-');
  } catch (e) {
    return timeString;
  }
};

const goToPublishArticle = () => {
  if (!isLoggedIn.value) {
    router.push('/login');
    return;
  }
  router.push('/publish');
};

const goToArticleDetail = (id: number) => {
  router.push(`/articles/${id}`);
};

onMounted(() => {
  fetchCarouselImages();
  fetchArticles();
});

const searchQuery = ref('');

const filteredArticles = computed(() => {
  if (!searchQuery.value) {
    return articles.value;
  }
  const query = searchQuery.value.toLowerCase();
  return articles.value.filter(article => {
    const titleMatch = article.title?.toLowerCase().includes(query);
    const bodyMatch = article.body?.toLowerCase().includes(query);
    return titleMatch || bodyMatch;
  });
});

const handleSearch = () => {
  // 搜索逻辑已通过 computed 属性实现
};

const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('此操作将永久删除该文章, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    const response = await axios.post('/api/demo/deleteitem', {
      delid: id,
      typeIndex: 1, 
    });

    if (response.data === 'del ok!!!') {
      ElMessage({
        type: 'success',
        message: '删除成功!',
      });
      // 删除成功后重新加载文章列表
      fetchArticles();
    } else {
      ElMessage({
        type: 'error',
        message: '删除失败: ' + response.data,
      });
    }
  } catch (error: any) {
    if (error === 'cancel') {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      });
    } else {
      ElMessage({
        type: 'error',
        message: '删除操作出错: ' + (error.message || error),
      });
    }
  }
};
</script>

<style scoped>

.user-status-bar {
  width: 100%;
  background: linear-gradient(90deg, #3896fb 0%, #6a82fb 100%);
  box-shadow: 0 2px 8px rgba(56, 150, 251, 0.08);
  border-bottom: 1px solid #e3eaf5;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 0 36px 0 0;
  min-height: 52px;
  font-size: 16px;
  margin-bottom: 18px;
  border-radius: 0 0 12px 12px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}
.user-info {
  margin-right: 16px;
  color: #fff;
  font-weight: 600;
  letter-spacing: 1px;
  font-size: 17px;
  display: flex;
  align-items: center;
  text-shadow: 0 1px 2px rgba(0,0,0,0.08);
}
.login-btn, .logout-btn {
  margin-left: 8px;
  border-radius: 18px !important;
  font-size: 15px;
  font-weight: 500;
  padding: 5px 18px;
  box-shadow: 0 2px 8px rgba(106,130,251,0.08);
  transition: background 0.2s, color 0.2s;
}
.login-btn {
  background: #fff !important;
  color: #3896fb !important;
  border: 1px solid #fff !important;
}
.login-btn:hover {
  background: #eaf2ff !important;
  color: #6a82fb !important;
}
.logout-btn {
  background: rgba(255,255,255,0.15) !important;
  color: #fff !important;
  border: 1px solid #fff2 !important;
}
.logout-btn:hover {
  background: #fc5c7d !important;
  color: #fff !important;
  border: 1px solid #fc5c7d !important;
}

.carousel-img-wrapper {
  position: relative;
}
.carousel-section {
  margin-bottom: 30px;
}
.carousel-img {
  width: 100%;
  height: 260px;
  object-fit: cover;
  border-radius: 8px;
}
.carousel-caption {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.4);
  color: #fff;
  padding: 12px 0;
  text-align: center;
  font-size: 1.2em;
  border-radius: 0 0 8px 8px;
  letter-spacing: 1px;
}
.articles-container {
  max-width: 900px;
  margin: 80px auto 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  position: relative;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

h2 {
  text-align: center;
  color: #333;
  font-size: 2.2em;
  font-weight: 700;
  margin: 0;
}

.publish-button {
  padding: 10px 20px;
  font-size: 1.1em;
  border-radius: 5px;
  background-color: #007bff;
  border-color: #007bff;
  transition: background-color 0.3s ease, border-color 0.3s ease;
}

.publish-button:hover {
  background-color: #0056b3;
  border-color: #0056b3;
}

.loading,
.error {
  text-align: center;
  font-size: 1.2em;
  color: #666;
  padding: 20px;
}

.error {
  color: #d9534f;
}

.article-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 25px;
}

.article-card {
  background-color: #ffffff;
  padding: 25px;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  cursor: pointer;
}

.article-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.article-title {
  color: #007bff;
  font-size: 1.5em;
  margin-top: 0;
  margin-bottom: 15px;
  line-height: 1.3;
}

.article-meta {
  font-size: 0.9em;
  color: #777;
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.article-meta .author {
  font-weight: bold;
}

.article-meta .time {
  margin-left: 10px;
}

.article-body {
  flex-grow: 1;
  margin-bottom: 15px;
}

.article-body p {
  font-size: 1em;
  color: #555;
  line-height: 1.6;
  margin-top: 0;
  margin-bottom: 0;
}

.article-body .no-body {
  font-style: italic;
  color: #999;
}

.article-details-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  border-top: 1px solid #eee;
  padding-top: 10px;
}

.article-details {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.delete-button {
  margin-left: 10px;
}
.article-details .detail-item {
  background-color: #e9ecef;
  padding: 5px 10px;
  border-radius: 5px;
}

.search-and-publish {
  display: flex;
  align-items: center;
  gap: 15px;
}

.search-input {
  width: 250px;
}

.no-results {
  text-align: center;
  font-size: 1.2em;
  color: #999;
  padding: 20px;
  grid-column: 1 / -1;
}
</style>
